#
# Rules for building project
#

# ----------------------------------------------------------------------------
# common targets and building rules
# ----------------------------------------------------------------------------
ELF_EXT = elf

# .elf file output path
ELF_FILE_PATH := $(OUT_DIR)/$(PRJ_NAME).$(ELF_EXT)

# ----------------------------------------------------------------------------
# extra include path
# ----------------------------------------------------------------------------
include $(MK_FILE_CC)

# ----------------------------------------------------------------------------
# linker script
# ----------------------------------------------------------------------------
# linker script, maybe override by the specific project
LINKER_SCRIPT ?= $(CHIP_PATH)/linker_script/gcc.ld

PROJECT_LD ?= $(OUT_DIR)/.project.ld

# ----------------------------------------------------------------------------
# library
# ----------------------------------------------------------------------------
# standard libraries
LIBRARIES += -lstdc++ -lsupc++ -lm -lc -lgcc

# POSIX libraries
LIBRARIES += -lpthread


# ----------------------------------------------------------------------------
# linker script
# ----------------------------------------------------------------------------

# ----------------------------------------------------------------------------
# flags for linker
# ----------------------------------------------------------------------------
LD_FLAGS = $(CPU) -Wl,--gc-sections \
	-Wl,-Map=$(basename $@).map,--cref \
	-pthread


# ----------------------------------------------------------------------------
# project rules
# ----------------------------------------------------------------------------
prj: $(ELF_FILE_PATH)

install: $(ELF_FILE_PATH)

install_clean:

%.objdump: %.$(ELF_EXT)
	@$(ECHO) "  DUMP    \033[34m$(@:$(PWD)/%=%)\033[0m"
	$(Q)$(OBJDUMP) -Sdh $< > $@

objdump: $(OUT_DIR)/$(PRJ_NAME).objdump

size: $(ELF_FILE_PATH)
	@$(ECHO) "  SIZE      "
	@$(ECHO) "---------------------------------------------------"
	$(Q)$(SIZE) $(OUT_DIR:$(shell pwd)/%=%)/$(PRJ_NAME).$(ELF_EXT)
	@$(ECHO) "---------------------------------------------------"

clean:
	@$(ECHO) "  CLEAN   \033[31m$@\033[0m"
	$(Q)-$(RM) \
	$(DEPS) \
	$(OBJS) \
	$(OUT_DIR)/$(PRJ_NAME).* \
	$(OUT_DIR)/$(PROJECT_LD) \
	$(OUT_DIR)/autoconf.h \
	$(OUT_DIR)/autoconf.mk \


$(ELF_FILE_PATH): $(OBJS) $(LINKER_SCRIPT) $(MAKEFILE_LIST)
	@$(ECHO) "  LD      \033[34m$(@:$(PWD)/%=%)\033[0m"
	$(Q)$(MD) $(dir $@)
	$(Q)$(CC) -E -P -CC $(INCLUDE_PATHS) $(CC_SYMBOLS) -o $(PROJECT_LD) - < $(LINKER_SCRIPT) && \
	$(CC) $(LD_FLAGS) -o$@ -T$(PROJECT_LD) -L$(OUT_DIR) $(EXT_SYMBOLS) $(OBJS) $(LIBRARIES)


